﻿using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using UtilZ.Dotnet.Ex.Base;

namespace UtilZ.Dotnet.Ex.DataStruct
{
    /// <summary>
    /// 速度限制器类
    /// </summary>
    public class SpeedLimiter<T> : IEnumerable<SpeedLimitItem>
    {
        /// <summary>
        /// 
        /// </summary>
        private readonly ConcurrentDictionary<T, SpeedLimitItem> _speedLimitDic = new ConcurrentDictionary<T, SpeedLimitItem>();


        /// <summary>
        /// 构造函数
        /// </summary>
        public SpeedLimiter()
        {

        }

        /// <summary>
        /// 添加一个限制项
        /// </summary>
        /// <param name="id">限制项标识</param>
        /// <param name="item">一个限制项</param>
        /// <exception cref="ArgumentNullException">限制项标识或一个限制项为null异常</exception>
        /// <exception cref="ArgumentException">限制项标识已存在异常</exception>
        public void Add(T id, SpeedLimitItem item)
        {
            if (id == null)
            {
                throw new ArgumentNullException(nameof(id));
            }

            if (item == null)
            {
                throw new ArgumentNullException(nameof(item));
            }

            if (this._speedLimitDic.TryAdd(id, item))
            {
                return;
            }
            else
            {
                throw new ArgumentException();
            }
        }

        /// <summary>
        /// 修改设置一个限制项
        /// </summary>
        /// <param name="id">限制项标识</param>
        /// <param name="item">一个限制项</param>
        /// <exception cref="ArgumentNullException">限制项标识或一个限制项为null异常</exception>
        public void Set(T id, SpeedLimitItem item)
        {
            if (id == null)
            {
                throw new ArgumentNullException(nameof(id));
            }

            if (item == null)
            {
                throw new ArgumentNullException(nameof(item));
            }

            this._speedLimitDic[id] = item;
        }

        /// <summary>
        /// 获取标识项指定的限制项
        /// </summary>
        /// <param name="id">限制项标识</param>
        /// <returns>限制项</returns>
        public SpeedLimitItem Get(T id)
        {
            SpeedLimitItem item;
            if (this._speedLimitDic.TryGetValue(id, out item))
            {
                return item;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 检查限制项是否已存在,存在返回true,不存在返回false
        /// </summary>
        /// <param name="id">限制项标识</param>
        /// <returns>存在返回true,不存在返回false</returns>
        public bool Exist(T id)
        {
            return this._speedLimitDic.ContainsKey(id);
        }

        /// <summary>
        /// 移除一个限制项,移除成功返回true,移除失败返回false
        /// </summary>
        /// <param name="id">限制项标识</param>
        /// <returns>移除成功返回true,移除失败返回false</returns>
        public bool Remove(T id)
        {
            SpeedLimitItem item;
            return this._speedLimitDic.TryRemove(id, out item);
        }

        /// <summary>
        /// 清空所有限制项
        /// </summary>
        public void Clear()
        {
            this._speedLimitDic.Clear();
        }


        /// <summary>
        /// 检查是否限制速度,限制返回true,不限制返回false
        /// </summary>
        /// <param name="id">限制项标识</param>
        /// <returns>限制返回true,不限制返回false</returns>
        public bool Check(T id)
        {
            SpeedLimitItem item;
            if (this._speedLimitDic.TryGetValue(id, out item))
            {
                return item.Check();
            }
            else
            {
                return false;
            }
        }


        /// <summary>
        /// 获取一个遍历枚举器
        /// </summary>
        /// <returns>遍历枚举器</returns>
        public IEnumerator<SpeedLimitItem> GetEnumerator()
        {
            return this._speedLimitDic.Values.GetEnumerator();
        }

        /// <summary>
        /// 获取一个遍历枚举器
        /// </summary>
        /// <returns>遍历枚举器</returns>
        IEnumerator IEnumerable.GetEnumerator()
        {
            return this._speedLimitDic.Values.GetEnumerator();
        }
    }

    /// <summary>
    /// 速度限制器项
    /// </summary>
    public class SpeedLimitItem
    {
        /// <summary>
        /// 限速选项
        /// </summary>
        private readonly SpeedLimitOption _option;
        /// <summary>
        /// 限速选项
        /// </summary>
        public SpeedLimitOption LimitOption
        {
            get { return this._option; }
        }

        /// <summary>
        /// 数据抽取倍数值,小于等于1不限制
        /// </summary>
        private readonly int _extractionMultiple = 0;

        /// <summary>
        /// 时间间隔,单位时间为100纳秒,小于等于0不限制
        /// </summary>
        private readonly long _timeInterval = 0L;

        /// <summary>
        /// 抽取倍数计数器
        /// </summary>
        private int _counter = 0;

        /// <summary>
        /// 时间计数器
        /// </summary>
        private long _lastTimestamp = 0;


        private static TicksTimestampFactory _timestampFactory;
        static SpeedLimitItem()
        {
            _timestampFactory = new TicksTimestampFactory(new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Local), TimestampUnit.Nanosecond100);
        }


        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="extractionMultiple">数据抽取倍数值,小于等于1不限制</param>
        public SpeedLimitItem(int extractionMultiple)
        {
            this._option = SpeedLimitOption.ExtractionMultiple;
            this._extractionMultiple = extractionMultiple;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="timeInterval">时间间隔,单位时间为100纳秒,小于等于0不限制</param>
        public SpeedLimitItem(long timeInterval)
        {
            this._option = SpeedLimitOption.TimeInterval;
            this._timeInterval = timeInterval;
        }

        /// <summary>
        /// 检查是否限制速度,限制返回true,不限制返回false
        /// </summary>
        /// <returns>限制返回true,不限制返回false</returns>
        internal bool Check()
        {
            if (this._option == SpeedLimitOption.TimeInterval)
            {
                if (this._timeInterval <= 0)
                {
                    return false;
                }

                var ts = _timestampFactory.GetTimestamp();
                if (ts - this._lastTimestamp > this._timeInterval)
                {
                    this._lastTimestamp = ts;
                    return true;
                }
            }
            else
            {
                if (this._extractionMultiple <= 1)
                {
                    return false;
                }

                if (Interlocked.Increment(ref this._counter) >= this._extractionMultiple)
                {
                    this._counter = 0;
                    return true;
                }
            }

            return false;
        }
    }

    /// <summary>
    /// 速度限制选项
    /// </summary>
    public enum SpeedLimitOption
    {
        /// <summary>
        /// 时间间隔
        /// </summary>
        TimeInterval,

        /// <summary>
        /// 数据抽取倍数
        /// </summary>
        ExtractionMultiple
    }
}
